package com.hunliji.monitor.web.mq.rocket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hunliji.common.exception.WarnException;
import com.hunliji.monitor.dao.utils.TemplateReplaceUtil;
import com.hunliji.monitor.manager.api.FeiShuManager;
import com.hunliji.monitor.manager.api.FeishuInterceptionManager;
import com.hunliji.monitor.manager.api.model.dto.FeiShuSendMsgDTO;
import com.hunliji.monitor.manager.api.model.param.FeiShuSendMsgManagerParam;
import com.hunliji.monitor.share.component.mq.rocket.RocketMqFacade;
import com.hunliji.monitor.share.component.mq.rocket.constants.RocketMqConstants;
import com.hunliji.monitor.share.enums.ReceiveIdTypeEnum;
import com.hunliji.monitor.share.enums.feishu.InterceptEventTypeEnum;
import com.hunliji.monitor.web.config.FeishuIssuePushConfig;
import com.hunliji.monitor.web.facade.FeiShuFacade;
import com.lark.project.core.utils.Lists;
import com.lark.project.service.field.model.FieldValuePair;
import com.lark.project.service.workitem.model.WorkItemInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RocketMQMessageListener(
        topic = RocketMqConstants.TOPIC_FEISHU_CREATE_ISSUE_DELAY,
        consumerGroup = RocketMqConstants.GROUP_FEISHU_CREATE_ISSUE_DELAY,
        selectorExpression = RocketMqConstants.TAG_FEISHU_CREATE_ISSUE_DELAY)
@Slf4j
public class FeishuCreateIssueMessageListener implements RocketMQListener<String> {

    @Resource
    private FeiShuManager feiShuManager;

    @Resource
    private FeiShuFacade feiShuFacade;

    @Resource
    private FeishuIssuePushConfig feishuIssuePushConfig;

    @Resource
    private FeishuInterceptionManager feishuInterceptionManager;

    @Resource
    private RocketMqFacade rocketMqFacade;

    @Override
    public void onMessage(String s) {
        log.info("FeishuDelayMessageListener receive msg:{}", s);

        JSONObject jsonObject = JSON.parseObject(s);
        JSONObject data = jsonObject.getJSONObject("data");
        String projectKey = data.getString("projectKey");
        String workItemTypeKey = data.getString("workItemTypeKey");
        String workItemName = data.getString("workItemName");

        String accessToken = feishuInterceptionManager.getAccessToken();
        // sdk的bug，无法使用工作项名称搜索，因此这里用原生http请求
        Long workItemId = feishuInterceptionManager.getWorkItemId(accessToken, projectKey, Lists.newArrayList(workItemTypeKey), workItemName);
        if (workItemId == null) {
            log.warn("未获取到对应工作项");
            return;
        }

        WorkItemInfo workItemInfo = feishuInterceptionManager.getWorkItemInfo(accessToken, workItemId, projectKey, workItemTypeKey);
        if (workItemInfo == null) {
            log.warn("未获取到对应工作项");
            return;
        }

        // 获取排雷视图
        List<Long> issueViewIds = feishuInterceptionManager.viewWorkItemList(accessToken, projectKey, feishuIssuePushConfig.getIssueViewId());
        if (!issueViewIds.contains(workItemId)) {
            log.info("视图不包含此缺陷，workItemInfo={}", JSON.toJSONString(workItemInfo));
            return;
        }
        // 排雷视图进行相关推送，首次进行钉钉群推送，5分钟未响应，则进行电话告警
        JSONObject message = getMessageFromTemplate(workItemInfo.getName(), workItemInfo.getFields(),  workItemInfo.getSubStage(), workItemInfo.getID());
        FeiShuSendMsgManagerParam sendParam = FeiShuSendMsgManagerParam.builder()
                .receiveIdType(ReceiveIdTypeEnum.CHAT_ID.getCode())
                .receiveId(feishuIssuePushConfig.getChatId())
                .content(message.toJSONString())
                .msgType("interactive")
                .build();
        FeiShuSendMsgDTO feiShuSendMsgDTO = feiShuManager.sendMsg(sendParam, feiShuFacade.getAccessToken());

        JSONObject delaySendResult = new JSONObject();
        delaySendResult.put("workItemId", workItemId);
        delaySendResult.put("type", InterceptEventTypeEnum.CREATE_WORK_ITEM.getEventType());
        delaySendResult.put("messageId", feiShuSendMsgDTO.getMessageId());
        delaySendResult.put("issueName", workItemInfo.getName());
        delaySendResult.put("projectKey", projectKey);
        delaySendResult.put("workItemTypeKey", workItemTypeKey);
        rocketMqFacade.delayedSend(RocketMqConstants.TOPIC_FEISHU_DELAY, RocketMqConstants.TAG_FEISHU_DELAY, delaySendResult.toJSONString(), RocketMqConstants.DelayLevel.FIVE_MINUTE);
    }

    @SuppressWarnings("unchecked")
    private JSONObject getMessageFromTemplate(String content, List<FieldValuePair> fields, String status, Long id) {
        Map<String, Object> priorityMap = (Map<String, Object>) fields.stream()
                .filter(fieldValuePair -> fieldValuePair.getFieldKey().equals("priority"))
                .findFirst()
                .map(FieldValuePair::getFieldValue)
                .orElse(new HashMap<>());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", content);
        resultMap.put("level", priorityMap.getOrDefault("label", "暂未定级").toString());
        resultMap.put("status", status);
        resultMap.put("userId", feishuIssuePushConfig.getUserOpenIds());
        resultMap.put("detailUrl", feishuIssuePushConfig.getDetailUrl() + id);
        resultMap.put("beginUrl", getBeginUrl(feishuIssuePushConfig.getBeginUrl(), id));

        return JSON.parseObject(TemplateReplaceUtil.replace(feishuIssuePushConfig.getCreateTemplate(), resultMap));
    }

    private String getBeginUrl(String beginUrl, Long id) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("workItemId", id);
        paramMap.put("type", InterceptEventTypeEnum.CREATE_WORK_ITEM.getEventType());
        return TemplateReplaceUtil.replace(beginUrl, paramMap);
    }

}
